package com.lwq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lwq.dao.system.PermissionMapper;
import com.lwq.dao.system.RolePermissionMapper;
import com.lwq.util.AnnotationManager;
import com.lwq.model.system.RelRolePermission;
import com.lwq.model.system.SysDict;
import com.lwq.model.system.SysPermission;
import com.lwq.service.system.DictService;
import com.lwq.util.RedisUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2021/6/9
 */
@SpringBootApplication
@MapperScan("com.lwq.dao")
@EnableSwagger2
@EnableScheduling
public class AdminApplication {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RedisUtil redis;
    @Autowired
    private DictService dictService;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Value("${token.expire}")
    private int tokenExpire;

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    public static void main(String[] args) {
        SpringApplication.run(AdminApplication.class, args);
    }

    /**
     * 项目启动的时候 把所有权限注解更新到权限表里
     */
    @PostConstruct
    public void initPermissions(){
        handlePermission();
        handleDictionary();
    }

    private void handleDictionary(){
        List<SysDict> dictList = dictService.queryList(null);
        if(!dictList.isEmpty()){
            redis.setCacheList("dict",dictList,tokenExpire, TimeUnit.HOURS);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void handlePermission(){
        this.logger.info("开始同步权限.....");
        List<SysPermission> permissionList = permissionMapper.selectList(null);
        List<SysPermission> permissionByAnno = AnnotationManager.getPermissionByAnno();
        //过滤出要删除的权限
        List<SysPermission> removeList = permissionList.stream().filter(e ->
                permissionByAnno.stream().filter(i -> i.getName().equals(e.getName()) &&
                        i.getCode().equals(e.getCode()) &&
                        i.getType().equals(e.getType())).count()<1).collect(Collectors.toList());
        removeList.forEach(e -> {
            rolePermissionMapper.delete(new QueryWrapper<RelRolePermission>().eq("permission_id", e.getId()));
            permissionMapper.deleteById(e.getId());
        });
        //过滤出要新增的权限
        List<SysPermission> saveList = permissionByAnno.stream().filter(e ->
                permissionList.stream().filter(i -> i.getName().equals(e.getName())
                        && i.getCode().equals(e.getCode()) && i.getType().equals(e.getType())).count()<1)
                .collect(Collectors.toList());
        //去重
        saveList = saveList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<SysPermission>(Comparator.comparing(o -> o.getName() + "#" + o.getType() + "#" + o.getCode()))), ArrayList::new));
        saveList.forEach(e -> {
            permissionMapper.insert(e);
        });
        this.logger.info("----->同步结束");
    }
}
